'use strict';

import { customer_accountModel } from "../model/customer_account";
import { ServiceBase, Exceptions } from '../kalend';
import { customer_addrService } from "./customer_addr";
import { sms } from '../middleware/sms';
import { usertokenService } from "./usertoken";
import { invitationService } from "./invitation";
import * as Koa from 'koa';
import { datadictionaryService } from "./datadictionary";
import { wineService } from "./wine";
import { mealService } from "./meal";
import { common } from "../middleware/common";
import { platform_userService } from "./platform_user";
import { roleService } from "./role";
import { userwinhistoryService } from "./userwinhistory";
import { excelnode } from '../middleware/excel4node';
import { merchantService } from "./merchant";
import { gifthistoryService } from "./gifthistory";
import { wechatService } from "./wechat";
import * as QRCodetorul from "qrcode";
import config from '../middleware/config';
import { fsfiles } from '../middleware/fsFiles';
import { qrcodeService } from './qrcode';
var moment = require('moment');

class Customer_accountService extends ServiceBase {
    configjson: any = config.get("wechat");
    // 二维码地址
    qrcodeurl: any = this.configjson["qrcodeurl"];
    constructor() {
        super(customer_accountModel)
    }
    /** 手机号登录小程序 */
    async login(phone: any, valite: any, token: any) {
        if (!token) {
            throw Exceptions.notoken();
        }
        if (!phone || phone.length != 11) {
            throw Exceptions.known('请输入合法手机号');
        }
        if (!valite) {
            throw Exceptions.known('请输入正确验证码');
        }
        if (valite.length != 6) {
            throw Exceptions.known('请输入6位短信验证码');
        }
        const uid = (await usertokenService.getToken(token)).userid;
        let data: any;
        // 添加审核测试账号
        if (phone === '13121563704') {
            data = await this.querySingle({ _id: uid, phone: phone, status: 1 }, { select: 'nickname name code coinbalance sex integral headimg' });
        } else {
            data = await this.querySingle({ _id: uid, phone: phone, validation: valite, status: 1 }, { select: 'nickname name code coinbalance sex integral headimg' });
        }
        if (data) {
            return data;
        } else {
            throw Exceptions.known('验证码输入错误');
        }
    }
    async queryinfo(token: any) {
        if (!token) {
            throw Exceptions.notoken();
        }
        const uid = (await usertokenService.getToken(token)).userid;
        let data = await this.querySingle({ _id: uid, status: 1 }, {
            select: 'nickname phone name code coinbalance mealbalance sex integral headimg ismember issupermember endtime isgetgift'
        });
        // 查询邀请记录
        data.invitation = await invitationService.queryCount(uid);
        //是否是餐厅
        // let resut = platform_userService.getSingleUser({ customerid: uid, roleId: "5d35a9ebdbba251bf079b584" });

        // if (resut) {
        //     data.ismerchant = true;
        // } else {
        //     data.ismerchant = false;
        // }
        //是否是品牌宣传大使
        // let puser = platform_userService.getSingleUser({ customerid: uid, roleId: "5b94cd656bbe2937c8fe5882" });
        // if (puser) {
        //     data.isagent = true;
        // } else {
        //     data.isagent = false;
        // }

        // 查询消费餐币\酒币数
        // data.mealDone = await mealService.getMeals(uid);
        // data.wineDone = await wineService.getWines(uid);

        return data;
    }
    async query(params: any) {
        const offset = params.offset;
        const limit = params.limit;
        const status = params.status;
        const name = params.name;
        const regstarttime = params.regstarttime;
        const regendtime = params.regendtime;
        const upstarttime = params.upstarttime;
        const upendtime = params.upendtime;
        const userid = params.userid;
        const isup = params.isup;
        const issuper = params.issuper;
        const isdiamond = params.isdiamond;
        const getgift = params.getgift;
        const filter: any = {};
        if (isup) {
            filter.ismember = true;
            if (!issuper) {
                filter.issupermember = { $ne: true };
            }
            if (!isdiamond) {
                filter.isdiamondmember = { $ne: true };
            } else {
                //filter.issupermember = true;
            }
        } else {
            let fi:Array<any> = [];
            if (issuper) {
                fi.push({
                    issupermember: true
                });
            }
            if (isdiamond) {
                fi.push({
                    isdiamondmember: true
                });
            }
            if(fi.length>0){
                filter.$or = fi;
            }
        }
        if (getgift) {
            filter.isgetgift = true;
        }
        if (name) {
            filter.$or = [{ nickname: { '$regex': name, $options: 'i' } }, { realname: { '$regex': name, $options: 'i' } }, { phone: { '$regex': name, $options: 'i' } }];
        }
        if (regstarttime) {
            filter.createTime = { '$gte': new Date(moment(new Date(regstarttime)).format('YYYY-MM-DD') + '  00:00:00') };
        }
        if (regendtime) {
            if (filter.createTime) {
                filter.createTime['$lte'] = new Date(moment(new Date(regendtime)).format('YYYY-MM-DD') + '  23:59:59');
            } else {
                filter.createTime = { '$lte': new Date(moment(new Date(regendtime)).format('YYYY-MM-DD') + '  23:59:59') };
            }
        }
        if (upstarttime) {
            filter.uptime = { '$gte': new Date(moment(new Date(upstarttime)).format('YYYY-MM-DD') + '  00:00:00') };
        }
        if (upendtime) {
            if (filter.uptime) {
                filter.uptime['$lte'] = new Date(moment(new Date(upendtime)).format('YYYY-MM-DD') + '  23:59:59');
            } else {
                filter.uptime = { '$lte': new Date(moment(new Date(upendtime)).format('YYYY-MM-DD') + '  23:59:59') };
            }
        }
        if (status === 0 || status === 1) {
            filter.status = status;
        }
        if (userid) {
            // const viters = await platform_userService.getviters(userid);
            // if (viters && viters.length > 0) {
            //     filter.inviter = { $in: viters };
            // }
            filter.agent = userid;
        }
        let result: any = await super.queryPagination(offset, limit, {
            filter: filter,
            populateOptions: {
                path: 'inviter',
                select: 'nickname'
            },
            select: 'inviter name code sex nickname phone coinbalance mealbalance createTime uptime endtime status ismember isdiamondmember issupermember isgetgift'
        });
        result.rows = result.rows.map((item: any) => {
            // if (item.phone) {
            //     item.phone = item.phone.substring(0, 3) + '****' + item.phone.substring(7, item.phone.length);
            // }
            
            if (item.isdiamondmember) {
                item.viplevel = '钻石会员';
            } else if (item.issupermember) {
                item.viplevel = '白金会员';
                if (item.isgetgift) {
                    item.giftstate = '已领取';
                } else {
                    item.giftstate = '未领取';
                }
            } else {
                if (item.ismember) {
                    item.viplevel = '黄金会员';
                } else {
                    item.viplevel = '';
                }
            }
            if (item.ismember) {
                item.ismember = '是';
            } else {
                item.ismember = '否';
            }

            if (item.status == 0) {
                item.status = '禁用';
            } else if (item.status == 1) {
                item.status = '有效';
            }
            if (item.inviter) {
                item.inviter = item.inviter.nickname;
            }
            return item;
        });
        if (userid) {
            filter.ismember = true;
            let success = await this.count(filter);
            let userdata = await platform_userService.queryById(userid);
            let znum = await this.count({ inviter: userdata.customerid, agent: userdata._id, ismember: true });
            result.footTotal = `邀请共计${result.total}位，成功申请会员${success}位，其中直招${znum}位，间接招募${success - znum}位`;
        } else {
            filter.ismember = true;
            let success = await this.count(filter);
            result.footTotal = `邀请共计${result.total}位，成功申请会员${success}位`;
        }
        return result;
    }
    async lock(userid: any) {
        return this.update(userid, { status: 0 });
    }
    async open(userid: any) {
        return this.update(userid, { status: 1 });
    }
    async setsender(userid: any) {
        return this.update(userid, { isender: true });
    }
    async nosender(userid: any) {
        return this.update(userid, { isender: false });
    }
    async save(ctx: Koa.Context) {
        let doc = ctx.request.body;
        let ip;
        const token = doc.token;
        if (!token) {
            throw Exceptions.notoken();
        }
        if (ctx.req.connection) {
            ip = ctx.req.connection.remoteAddress;
        }

        let res: any;

        if (ip) {
            doc.loginip = ip;
        }
        // if (!doc.headimg) {
        //     doc.headimg = '/static/images/touxiang.jpg';
        // }
        // if (!doc.nickname) {
        //     doc.nickname = '点击头像获取微信昵称';//common.buildCode();
        // }
        let tokendata = await usertokenService.getToken(token);
        let user = await this.querySingle({ _id: tokendata.userid }, { select: 'appcode inviter intercode ismember headimg nickname' });
        if (user) {
            if (doc.ivtercode && doc.ivtercode !== user.ivtercode && !user.ismember) {
                // 生成邀请记录
                this.buildivterhistory(doc.ivtercode, tokendata.userid);
            }
            console.log('用户原本信息');
            console.log(common.json2Xml(user));
            user = this.pars(doc, user);
            if (!user.headimg) {
                console.log('用户初始化头像');
                user.headimg = '/static/images/touxiang.jpg';
            }
            if (!user.nickname) {
                console.log('用户初始化昵称');
                user.nickname = '点击头像获取资料';
            }
            console.log('更新用户信息');
            console.log(common.json2Xml(user));
            res = await this.update(user._id, user);
        } else {
            // if (doc.ivtercode) {
            //     // 生成邀请记录
            //     this.buildivterhistory(doc.ivtercode, tokendata.userid);
            // }
            if (!doc.headimg) {
                console.log('用户初始化头像');
                doc.headimg = '/static/images/touxiang.jpg';
            }
            if (!doc.nickname) {
                console.log('用户初始化昵称');
                doc.nickname = '点击头像获取资料';
            }
            console.log('创建用户信息');
            console.log('创建用户');
            console.log(common.json2Xml(doc));
            res = await this.creatnew(doc);
        }
        if (user.loginip || user.longitude || user.latitude) {
            customer_addrService.create({ userid: user._id, longintime: new Date, loginip: user.loginip, longitude: user.longitude, latitude: user.latitude });
        }
        return '用户信息保存成功';
    }

    async sendsms(token: any, phone: any, type?: Number) {
        if (!token) {
            throw Exceptions.notoken();
        }
        if (!phone || phone.length != 11) {
            throw Exceptions.known("手机号不合法");
        }
        const tokedata = await usertokenService.getToken(token);
        const session_key = tokedata.session_key;
        const openid = tokedata.openid;
        const appcode = tokedata.appcode;
        // let user = await this.exist({ _id: new ObjectId(uid) });
        // let newuser: any;
        //避免要改动发送的信息内容，所以从数据库读取短信信息
        // let results: string = await datadictionaryService.querybyKey('validation');
        //按规则生成验证码后发送短信
        let validation = Math.round(Math.random() * 1000000).toString();
        console.log(phone + '短信验证码为：' + validation);
        if (validation.length < 6) {
            for (let i = 0; i < 6 - validation.length; i++) {
                validation = '3' + validation;
            }
        }
        // let result: string = results.replace('validation', validation);
        console.log(phone + '短信验证码规则后为：' + validation);
        sms.sendmsg(validation, phone, type);
        // 发送验证码后更新信息
        console.log('查询用户不存在，创建新用户');
        customer_accountService.creatnew({ phone: phone, validation: validation, openid: openid, session_key: session_key, appcode: appcode, tokenid: tokedata._id });
        // if (user) {
        //     await this.update(uid, { phone: phone, validation: validation });
        // } else {
        //     newuser = await this.create({ phone: phone, validation: validation, openid: openid });
        // }
        return '发送成功';
    }
    pars(parms: any, model: any) {
        for (const key in parms) {
            if (parms[key]) {
                model[key] = parms[key];
            }
        }
        console.log(common.json2Xml(model));
        return model;
    }
    async creatnew(doc: any) {
        let res: any;
        let user = await this.querySingle({ phone: doc.phone });
        if (user) {
            if (user.status === 1) {
                console.log(doc.ivtercode);
                if (doc.ivtercode !== user.ivtercode && !user.ismember) {
                    // 生成邀请记录
                    this.buildivterhistory(doc.ivtercode, user._id);
                }
                console.log('用户存在，更新用户');
                user = this.pars(doc, user);
                res = await this.update(user._id, user);
            } else if (user.status === 0) {
                console.log('用户已被禁用');
                throw Exceptions.known('用户已被禁用');
            }
        } else {
            console.log('查询用户不存在，创建新用户');
            res = await this.create(doc);
            console.log(doc.ivtercode);
            if (doc.ivtercode) {
                // 生成邀请记录
                this.buildivterhistory(doc.ivtercode, res._id);
            }
        }
        // 更新token用户信息
        let tokend = await usertokenService.querySingle({ _id: doc.tokenid, userid: res._id });
        if (!tokend) {
            console.log('更新token用户id');
            usertokenService.update(doc.tokenid, { userid: res._id });
        }
        return res;
    }
    async buildivterhistory(ivtercode: any, uid: any) {
        console.log('生成邀请记录');
        const inver = await this.querySingle({ code: ivtercode }, { select: 'code name legaluserid agent' });
        if (inver && uid.toJSON() !== inver._id.toJSON()) {
            // 根据邀请人小程序查询
            let doc: any = {
                inviter: inver._id,
                agent: null,
                legaluserid: null
            };
            // 大使邀请奖励，无限裂变，不需要请注释 start
            if (inver.agent) {
                doc.agent = inver.agent;
                doc.agentlevel = 2;
            }
            // 大使邀请奖励，无限裂变，不需要请注释 end

            // 餐厅邀请奖励，无限裂变，不需要请注释 start
            // else if (inver.legaluserid) {
            //     doc.legaluserid = inver.legaluserid;
            // } 
            // 餐厅邀请奖励，无限裂变，不需要请注释 end

            // 以下为一级裂变，大使和餐厅皆可
            //else {
            // 判断邀请人是否为大使
            let role = (await roleService.queryalls({ name: { $regex: '品牌宣传', $options: 'i' } })).map((a) => {
                return a._id;
            });
            const isds = await platform_userService.querySingle({
                customerid: inver._id,
                roleId: { $in: role }
            });
            if (isds) {
                doc.agent = isds._id;
                doc.agentlevel = 1;
            }
            // 判断邀请人是否为餐厅负责人
            const rolect = await roleService.querySingle({ name: { $regex: '餐厅', $options: 'i' } });
            const isct = await platform_userService.querySingle({
                customerid: inver._id,
                roleId: { $in: [rolect._id] }
            });
            if (isct) {
                doc.legaluserid = isct._id;
            }
            //}

            this.update(uid, doc);
            const isexce = await invitationService.exist({ customerid: uid, inviter: inver._id });
            if (!isexce) {
                let cre: any = {
                    customerid: uid,
                    inviter: inver._id,
                    isupvip: false,
                    isgive: false
                };
                if (doc.agent) {
                    cre.agent = doc.agent;
                    cre.agentlevel = doc.agentlevel;
                }
                if (doc.legaluserid) {
                    cre.legaluserid = doc.legaluserid;
                    const pus = await platform_userService.queryById(doc.legaluserid);
                    cre.merchantid = pus.merchantid;
                }
                invitationService.create(cre);
            }
        }
    }

    // 会员升级成功调用方法
    async upvipsuccess(orderdata: any) {
        let datdic = await datadictionaryService.querybyKey('membership');
        if (!datdic) {
            console.log('升级会员信息未设置，请联系管理员');
        }

        let userdata = await this.querySingle({ _id: orderdata.customerid, status: 1 }, { select: 'coinbalance inviter nickname phone' });
        let endtime = new Date();
        endtime.setFullYear(endtime.getFullYear() + 1);
        let conins = 0;
        let upcoin = userdata.coinbalance;
        let source = 2;
        if (orderdata.ordertype === '升级白金会员') {
            source = 6;
            conins = (datdic.find((a: any) => {
                return a.code == 'superconins';
            })).count;
            upcoin = upcoin + conins;
            this.update(userdata._id, { coinbalance: upcoin, ismember: true, issupermember: true, uptime: new Date(), endtime: endtime });
            // 添加礼品领取记录，默认未领取
            let doc: any = {
                userid: userdata._id,
                nickname: userdata.nickname,
                phone: userdata.phone
            };
            gifthistoryService.create(doc);
        } else if (orderdata.ordertype === '升级钻石会员') {
            source = 7;
            conins = (datdic.find((a: any) => {
                return a.code == 'diamondconins';
            })).count;
            upcoin = upcoin + conins;
            this.update(userdata._id, { coinbalance: upcoin, ismember: true, isdiamondmember: true, uptime: new Date(), endtime: endtime });
        } else {
            conins = (datdic.find((a: any) => {
                return a.code == 'conins';
            })).count;
            upcoin = upcoin + conins;
            this.update(userdata._id, { coinbalance: upcoin, ismember: true, uptime: new Date(), endtime: endtime });
        }
        console.log('升级会员：增加用户酒币成功');

        // 增加酒币消费记录
        let doc: any = {
            openid: orderdata.openid,
            orderid: orderdata._id,
            source: source,
            userid: orderdata.customerid,
            originwine: userdata.coinbalance,
            conins: conins,
            coinbalance: upcoin
        };
        wineService.create(doc);
        console.log('升级会员：增加酒币消费记录成功');

        // 增加邀请人餐币
        let mealbalance = (datdic.find((a: any) => {
            return a.code == 'mealbalance';
        })).count;

        // 更新邀请人奖励
        this.updateInviter(orderdata, userdata.inviter, mealbalance);
    }

    // 活动抽奖增加酒币
    async addcoins(uid: any, conins: Number) {
        let user = await this.querySingle({ _id: uid, status: 1 }, { select: 'coinbalance' });
        let newcoins = user.coinbalance + conins;
        console.log('抽奖活动：用户中奖');
        this.update(uid, { coinbalance: newcoins });
        console.log('抽奖活动：用户酒币+' + conins);

        // 创建酒币消费记录
        let doc: any = {
            userid: uid,
            originwine: user.coinbalance,
            conins: conins,
            coinbalance: newcoins,
            source: 4,
            remark: '中奖酒币+' + conins
        };
        wineService.create(doc);
        console.log('抽奖活动：增加用户酒币消费记录');
    }

    // 更新邀请人奖励
    async updateInviter(orderdata: any, inviter: any, mealbalance: any) {
        if (inviter) {
            const vipuser = await customer_accountService.querySingle(
                { _id: orderdata.customerid, status: 1 },
                {
                    populateOptions: [
                        {
                            path: 'agent',
                            select: 'customerid'
                        },
                        {
                            path: 'legaluserid',
                            select: 'customerid'
                        }
                    ],
                    select: 'agent legaluserid inviter agentlevel isdiamondmember'
                });
            // 如果是大使一级下线，奖励大使15元，二级下线，奖励大使5元
            if (vipuser.agent) {
                let bos = await platform_userService.querySingle({ _id: vipuser.agent._id }, { select: 'balancezm' });

                let addmoney = 10; //await userwinhistoryService.getlevel(vipuser.agent._id);
                if (vipuser.agentlevel == 1) {
                    addmoney = 15;
                } else if (vipuser.agentlevel == 2) {
                    addmoney = 5;
                }
                const newbalance = common.add(bos.balancezm || 0, addmoney);
                platform_userService.update(bos._id, { balancezm: newbalance });

                // 增加奖励记录
                let doc: any = {
                    balance: newbalance,
                    money: addmoney,
                    originbalance: bos.balancezm || 0,
                    platform_user: bos._id,
                    customerid: orderdata.customerid,
                    inviterid: inviter,
                    customerorderid: orderdata._id
                };

                if (vipuser.legaluserid) {
                    const merdata = await merchantService.querySingle({ legaluserid: vipuser.legaluserid._id });
                    if (merdata) {
                        doc.merchantid = merdata._id;
                    }
                }

                userwinhistoryService.create(doc);
                console.log(`升级会员：增加会员所属大使奖励${addmoney}元成功`);
            }
            // 如果是餐厅法人下线，奖励餐厅法人10元
            if (vipuser.legaluserid) {
                let bos = await platform_userService.querySingle({ _id: vipuser.legaluserid._id }, { select: 'balance' });
                let addmoney = vipuser.isdiamondmember ? 70 : 10;//await userwinhistoryService.getlevel(vipuser.legaluserid._id);
                const merdata = await merchantService.querySingle({ legaluserid: vipuser.legaluserid._id });
                const newbalance = common.add(bos.balance || 0, addmoney);
                platform_userService.update(bos._id, { balance: newbalance });
                // 增加奖励记录
                let doc: any = {
                    balance: newbalance,
                    money: addmoney,
                    originbalance: bos.balance || 0,
                    platform_user: bos._id,
                    customerid: orderdata.customerid,
                    inviterid: inviter,
                    customerorderid: orderdata._id
                };
                if (merdata) {
                    doc.merchantid = merdata._id;
                }
                userwinhistoryService.create(doc);
                console.log(`升级会员：增加会员所属餐厅法人奖励${addmoney}元成功`);
            }
            // 如果邀请人和大使是同一人（一级裂变体验），只奖励大使10元，不再奖励餐币
            // 如果邀请人和餐厅法人是同一人（一级裂变体验），只奖励餐厅法人10元，不再奖励餐币
            if ((vipuser.agent && vipuser.agent.customerid && vipuser.agent.customerid.toJSON() === vipuser.inviter.toJSON()) || (vipuser.legaluserid && vipuser.legaluserid.customerid && vipuser.legaluserid.customerid.toJSON() === vipuser.inviter.toJSON())) {

            } else {
                console.log('升级会员：增加邀请人餐币开始');
                let inviterData = await customer_accountService.querySingle({ _id: inviter, status: 1 }, { select: ' mealbalance' });
                const upmealbalance = common.add(inviterData.mealbalance || 0, Number(mealbalance));
                customer_accountService.update(inviterData._id, { mealbalance: upmealbalance });
                console.log(`升级会员：邀请人餐币+${mealbalance}成功`);

                // 增加餐币消费记录
                let doc: any = {
                    openid: orderdata.openid,
                    orderid: orderdata._id,
                    source: 3,
                    sourceuid: orderdata.customerid,
                    userid: inviter,
                    originmeal: inviterData.mealbalance || 0,
                    meal: mealbalance,
                    mealbalance: upmealbalance
                };
                mealService.create(doc);
                // 增加奖励记录
                let doc2: any = {
                    balance: upmealbalance,
                    money: mealbalance,
                    originbalance: inviterData.mealbalance || 0,
                    customerid: orderdata.customerid,
                    inviterid: inviter,
                    customerorderid: orderdata._id
                };
                userwinhistoryService.create(doc2);
                console.log('升级会员：增加邀请人餐币消费记录成功');
            }
            // 更新邀请记录
            invitationService.updatestate(orderdata.customerid, inviter, orderdata.money, mealbalance);
            console.log('升级会员：更新邀请记录成功');
            console.log('升级会员：更新邀请人信息结束');
        }
    }
    // 更新邀请人奖励
    async updateInviter_bak831(orderdata: any, inviter: any, mealbalance: any) {
        if (inviter) {
            let role = await roleService.querySingle({ name: { $regex: '品牌宣传', $options: 'i' } });
            let plauser = await platform_userService.querySingle({ customerid: inviter }
                , {
                    populateOptions: {
                        path: 'merchantid',
                        select: 'agent'
                    }
                });
            // 会员邀请赠送餐币
            if (!plauser) {
                console.log('升级会员：更新会员信息开始');
                let inviterData = await customer_accountService.querySingle({ _id: inviter, status: 1 }, { select: ' mealbalance inviter' });
                const upmealbalance = common.add(Number(inviterData.mealbalance) || 0, Number(mealbalance));
                customer_accountService.update(inviterData._id, { mealbalance: upmealbalance });
                console.log('升级会员：增加会员餐币成功');

                // 增加餐币消费记录
                orderdata.meal = mealbalance;
                let doc: any = {
                    openid: orderdata.openid,
                    orderid: orderdata._id,
                    source: 3,
                    sourceuid: orderdata.customerid,
                    userid: inviter,
                    originmeal: inviterData.mealbalance || 0,
                    meal: mealbalance,
                    mealbalance: upmealbalance
                };
                mealService.create(doc);
                console.log('升级会员：增加会员餐币消费记录成功');

                /** 如果邀请会员有所属大使 */
                if (inviterData.inviter && role) {
                    const bos = await platform_userService.querySingle({
                        customerid: inviterData.inviter,
                        roleId: { $in: [role._id] }
                    });
                    // 大使奖励10元
                    if (bos) {
                        const addmoney = await userwinhistoryService.getlevel(bos._id);
                        const newbalance = common.add(Number(bos.balance) || 0, addmoney);
                        platform_userService.update(bos._id, { balance: newbalance });
                        // 增加奖励记录
                        let doc: any = {
                            balance: newbalance,
                            money: addmoney,
                            originbalance: bos.balance || 0,
                            platform_user: bos._id,
                            customerid: orderdata.customerid,
                            inviterid: inviter,
                            customerorderid: orderdata._id
                        };
                        userwinhistoryService.create(doc);
                        console.log(`升级会员：增加会员所属大使奖励${addmoney}元成功`);
                    }
                }
            } else {
                // 邀请人是餐厅赠送10元
                if (plauser.merchantid) {
                    const newbalance = common.add(Number(plauser.balance) || 0, 10);
                    platform_userService.update(plauser._id, { balance: newbalance });
                    // 增加奖励记录
                    let doc: any = {
                        balance: newbalance,
                        money: 10,
                        originbalance: plauser.balance || 0,
                        platform_user: plauser._id,
                        merchantid: plauser.merchantid._id,
                        customerid: orderdata.customerid,
                        inviterid: inviter,
                        customerorderid: orderdata._id
                    };
                    userwinhistoryService.create(doc);
                    console.log('升级会员：增加会员所属餐厅奖励10元成功');

                    // 邀请人是餐厅所属大使
                    if (plauser.merchantid.agent) {
                        const agent = await platform_userService.queryById(plauser.merchantid.agent);
                        const addmoney = await userwinhistoryService.getlevel(agent._id);
                        const newbalance2 = common.add(Number(agent.balance) || 0, addmoney);
                        platform_userService.update(agent._id, { balance: newbalance2 });
                        // 增加奖励记录
                        let doc: any = {
                            balance: newbalance2,
                            money: addmoney,
                            originbalance: agent.balance || 0,
                            platform_user: agent._id,
                            customerid: orderdata.customerid,
                            merchantid: plauser.merchantid._id,
                            inviterid: inviter,
                            customerorderid: orderdata._id
                        };
                        userwinhistoryService.create(doc);
                        console.log(`升级会员：增加会员所属餐厅所属大使奖励${addmoney}元成功`);
                    }
                } else {
                    // 邀请人是宣传大使
                    if (plauser.roleId && plauser.roleId.length > 0 && role) {
                        if ((plauser.roleId as Array<any>).findIndex((a) => {
                            return a.toJSON() === role._id.toJSON();
                        }) >= 0) {
                            const addmoney = await userwinhistoryService.getlevel(plauser._id);
                            const newbalance = common.add(Number(plauser.balance) || 0, addmoney);
                            platform_userService.update(plauser._id, { balance: newbalance });
                            // 增加奖励记录
                            let doc: any = {
                                balance: newbalance,
                                money: addmoney,
                                originbalance: plauser.balance || 0,
                                platform_user: plauser._id,
                                customerid: orderdata.customerid,
                                inviterid: inviter,
                                customerorderid: orderdata._id
                            };
                            userwinhistoryService.create(doc);
                            console.log(`升级会员：增加会员所属大使奖励${addmoney}元成功`);
                        }
                    }
                }
            }




            // 更新邀请记录
            invitationService.updatestate(orderdata.customerid, inviter, orderdata.money, mealbalance);
            console.log('升级会员：更新邀请记录成功');
            console.log('升级会员：更新邀请人信息结束');
        }
    }

    // 初始化到期日期
    async initdate() {
        let data = await this.queryAll({ filter: { uptime: { $exists: true } } });
        data.forEach((item) => {
            item.endtime = moment(item.uptime).add(1, 'year');
            this.update(item._id, { endtime: item.endtime })
        })
    }
    /** 导出列表数据  : Promise<IDownloadType> */
    async export(parms: any) {
        parms.offset = Number.MAX_SAFE_INTEGER;
        parms.limit = 0;
        let result = (await this.query(parms)).rows;
        if (result && result.length > 0) {
            let heads = ["序号",
                "昵称",
                "手机号",
                "酒币",
                "酒币过期日期",
                "注册日期",
                "升级日期",
                "邀请人",
                "状态"];
            let json: any = [];
            result.forEach((item: any, i: any) => {
                const rowdata: Array<any> = [];
                rowdata.push((i + 1).toString());//序号
                rowdata.push(item.nickname);
                rowdata.push(item.phone);
                rowdata.push(item.coinbalance);
                rowdata.push(item.endtime ? moment(item.endtime).format('YYYY-MM-DD HH:mm') : '');
                rowdata.push(item.createTime ? moment(item.createTime).format("YYYY-MM-DD HH:mm") : '');
                rowdata.push(item.uptime ? moment(item.uptime).format("YYYY-MM-DD HH:mm") : '');
                rowdata.push(item.inviter);
                rowdata.push(item.status);
                json.push(rowdata);
            })
            return excelnode(heads, json)
        }
    }

    async upwine(doc: any) {
        // 更新用户酒币数
        const cuser = await this.queryById(doc.id);
        if (doc.utype === '酒币') {
            let newcoins = cuser.coinbalance;
            // 增加酒币消费记录
            let newdoc: any = {
                source: 5,
                upuser: doc.userid,
                originwine: doc.num,
                userid: cuser._id
            };
            if (doc.uptype === 'add') {
                newcoins += Number(doc.number);
                newdoc.conins = doc.number;
            } else {
                newcoins -= Number(doc.number);
                newdoc.conins = doc.number;
            }
            newdoc.coinbalance = newcoins;

            this.update(cuser._id, { coinbalance: newcoins });
            wineService.create(newdoc);
            console.log('修改会员：增加酒币消费记录成功');
        } else if (doc.utype === '餐币') {
            let newcoins = cuser.mealbalance || 0;
            // 增加餐币消费记录
            let newdoc: any = {
                source: 5,
                upuser: doc.userid,
                originwine: doc.num,
                userid: cuser._id
            };
            if (doc.uptype === 'add') {
                newcoins += Number(doc.number);
                newdoc.meal = doc.number;
            } else {
                newcoins -= Number(doc.number);
                newdoc.meal = doc.number;
            }
            newdoc.mealbalance = newcoins;

            this.update(cuser._id, { mealbalance: newcoins });
            mealService.create(newdoc);
            console.log('修改会员：增加餐币消费记录成功');
        }

    }

    async getuserinfobyphone(doc: any) {
        return await this.querySingle({ phone: doc.phone });
    }

    async getGift(token: any) {
        if (!token) {
            throw Exceptions.notoken();
        }
        const uid = (await usertokenService.getToken(token)).userid;
        if (uid) {
            let data = await this.querySingle({ _id: uid, status: 1 }, {
                select: 'ismember issupermember isgetgift'
            });
            // if (!data.ismember) {
            //     throw Exceptions.known('请先升级会员，才能领取礼品哦！');
            // }
            if (!data.issupermember) {
                throw Exceptions.known('请升级白金会员，才能领取礼品');
            }
            if (data.isgetgift) {
                throw Exceptions.known('礼品已领取');
            }
            await this.update(uid, { isgetgift: true });
            // 更新礼品领取状态
            gifthistoryService.upstate(uid);
            return {
                msg: '领取成功'
            };
        } else {
            throw Exceptions.known('未获取到用户信息，领取失败');
        }
    }
    async getGift2(token: any) {
        if (!token) {
            throw Exceptions.notoken();
        }
        const uid = (await usertokenService.getToken(token)).userid;
        if (uid) {
            let data = await this.querySingle({ _id: uid, status: 1 }, {
                select: 'ismember issupermember isgetgift'
            });
            // if (!data.ismember) {
            //     throw Exceptions.known('请先升级会员，才能领取礼品哦！');
            // }
            if (!data.issupermember) {
                throw Exceptions.known('请升级白金会员，才能领取礼品');
            }
            if (data.isgetgift) {
                throw Exceptions.known('礼品已领取');
            }
            let url = `https://api.shmixin.cn/fh/fh.html?userid=${uid}`;

            let pars: any = {
                userid: uid
            };
            return await wechatService.Qrcode(url, 'getgift', pars);
        } else {
            throw Exceptions.known('请先登录，领取失败');
        }
    }

    async getGift3(token: any) {
        if (!token) {
            throw Exceptions.notoken();
        }
        const uid = (await usertokenService.getToken(token)).userid;
        if (uid) {
            let data = await this.querySingle({ _id: uid, status: 1 }, {
                select: 'ismember issupermember isgetgift'
            });
            if (!data.issupermember) {
                throw Exceptions.known('只有白金会员，才能领取礼品');
            }
            if (data.isgetgift) {
                throw Exceptions.known('礼品已领取');
            }
            return '可领取礼品';
        }
    }



    async GetUserQrCode(doc: any) {
        const user = await customer_accountService.querySingle({ _id: doc.userid }, { select: 'code' });
        let url = this.qrcodeurl;
        if (user) {
            url += user.code;
        }
        try {
            let a = await QRCodetorul.toDataURL(url, { width: 480 });
            let filepath = await fsfiles.baseimgwrite(a, doc.userid + '.png');
            qrcodeService.create({
                userid: doc.userid,
                url: filepath,
                qrcodeurl: url
            });
            return filepath;
        } catch (error) {
            console.log(error)
            return null;
        }
    }

}

export const customer_accountService = new Customer_accountService();